﻿@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Edit Claim Page";

    bool hasError = false;
    string errorMessage = string.Empty;
    bool hasSuccess = false;
    string successMessage = string.Empty;

    string frm_claimDate = string.Empty;
    string frm_claimShiftType = string.Empty;
    string frm_claimStartWorkTime = string.Empty;
    string frm_claimEndWorkTime = string.Empty;
    string frm_claimStartOT = string.Empty;
    string frm_claimEndOT = string.Empty;

    string frm_claimHours_OT1_5 = string.Empty;
    string frm_claimHours_OT2_0 = string.Empty;
    string frm_claimHours_PH = string.Empty;
    string frm_claimHours_Less4H = string.Empty;
    string frm_claimHours_More4H = string.Empty;

    string frm_claimAllowance_Shift = string.Empty;
    string frm_claimAllowance_Meal = string.Empty;
    string frm_claimRemark = string.Empty;
    string frm_claimTotalOTHours = "N/A";
    string frm_claimBreakHours = string.Empty;

    KeppelLand.Entities.Claim claim = null;
    List<KeppelLand.Entities.Claim> claimList = null;
    KeppelLand.Entities.ClaimSummary claimSummary = null;
    
    System.Data.DataSet ds = new System.Data.DataSet("CurrentClaims");
    
    if (IsPost)
    {
        if (Request.Form["actionButton"] == "update")
        {
            frm_claimDate = Request.Form["claimDate"].Trim();
            frm_claimShiftType = Request.Form["claimShiftType"].Trim();
            frm_claimStartWorkTime = Request.Form["claimStartWorkTime"].Trim();
            frm_claimEndWorkTime = Request.Form["claimEndWorkTime"].Trim();
            frm_claimStartOT = Request.Form["claimStartOT"].Trim();
            frm_claimEndOT = Request.Form["claimEndOT"].Trim();
            frm_claimHours_OT1_5 = Request.Form["claimHours_OT1_5"].Trim();
            frm_claimHours_OT2_0 = Request.Form["claimHours_OT2_0"].Trim();
            frm_claimHours_PH = KeppelLand.Helpers.TranslationHelper.GetCheckboxFormValue(Request.Form["claimHours_PH"]);
            frm_claimHours_Less4H = KeppelLand.Helpers.TranslationHelper.GetCheckboxFormValue(Request.Form["claimHours_Less4H"]);
            frm_claimHours_More4H = KeppelLand.Helpers.TranslationHelper.GetCheckboxFormValue(Request.Form["claimHours_More4H"]);
            frm_claimAllowance_Shift = Request.Form["claimAllowance_Shift"].Trim();
            frm_claimAllowance_Meal = Request.Form["claimAllowance_Meal"].Trim();
            frm_claimRemark = Request.Form["claimRemark"].Trim();

            KeppelLand.Entities.Claim newClaim = new KeppelLand.Entities.Claim();
            newClaim.ClaimDate = DateTime.ParseExact(frm_claimDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
            newClaim.ShiftType = frm_claimShiftType;
            newClaim.Remark = frm_claimRemark;

            DateTime p_DateTime;

            if (DateTime.TryParseExact(frm_claimStartWorkTime, "HHmm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out p_DateTime))
            {
                newClaim.StartWorkTime = newClaim.ClaimDate.Add(p_DateTime - DateTime.Today);
            }
            if (DateTime.TryParseExact(frm_claimEndWorkTime, "HHmm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out p_DateTime))
            {
                newClaim.EndWorkTime = newClaim.ClaimDate.Add(p_DateTime - DateTime.Today);
            }
            if (DateTime.TryParseExact(frm_claimStartOT, "HHmm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out p_DateTime))
            {
                newClaim.StartOverTime = newClaim.ClaimDate.Add(p_DateTime - DateTime.Today);
            }
            if (DateTime.TryParseExact(frm_claimEndOT, "HHmm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out p_DateTime))
            {
                newClaim.EndOverTime = newClaim.ClaimDate.Add(p_DateTime - DateTime.Today);
            }

            if ((newClaim.StartOverTime.HasValue && newClaim.EndOverTime.HasValue) &&
                (newClaim.StartOverTime.Value.ToString("tt") == "PM") &&
                (newClaim.EndOverTime.Value.ToString("tt") == "AM"))
            {
                newClaim.EndOverTime = newClaim.EndOverTime.Value.AddDays(1);
            }

            newClaim.OT1_5 = KeppelLand.Helpers.TranslationHelper.ParseDecimal(frm_claimHours_OT1_5);
            newClaim.OT2_0 = KeppelLand.Helpers.TranslationHelper.ParseDecimal(frm_claimHours_OT2_0);
            newClaim.PH = KeppelLand.Helpers.TranslationHelper.ParseBoolean(frm_claimHours_PH);
            newClaim.RD4 = KeppelLand.Helpers.TranslationHelper.ParseBoolean(frm_claimHours_Less4H);
            newClaim.RD8 = KeppelLand.Helpers.TranslationHelper.ParseBoolean(frm_claimHours_More4H);
            newClaim.AlwMeal = KeppelLand.Helpers.TranslationHelper.ParseDecimal(frm_claimAllowance_Meal);
            newClaim.AlwShft = KeppelLand.Helpers.TranslationHelper.ParseDecimal(frm_claimAllowance_Shift);

            decimal totalOTClaimed = 0;
            if (newClaim.OT1_5.HasValue && newClaim.OT2_0.HasValue)
            {
                totalOTClaimed = newClaim.OT1_5.Value + newClaim.OT2_0.Value;
            }
            
            // Validation rules
            //if (p_claimEndOT.Subtract(p_claimStartOT).TotalHours != (double)totalOTClaimed)
            //{
            //    hasError = true;
            //    errorMessage = errorMessage + string.Format("You have clocked {0} hours but are claiming {1} hours.",
            //        p_claimEndOT.Subtract(p_claimStartOT).TotalHours,
            //        totalOTClaimed);
            //}

            if (!hasError)
            {
                try
                {
                    if ((Request.QueryString.Count > 0) && (Request.QueryString["ID"] != null))
                    {
                        string id = KeppelLand.Helpers.CryptographyHelper.Decrypt(Request.QueryString["ID"]);
                        if (KeppelLand.Controllers.ClaimController.UpdateClaim(id, newClaim))
                        {
                            hasSuccess = true;
                            successMessage = "Claim entry updated.";
                            
                            Session["successMessage"] = successMessage;
                            
                            Response.Redirect("New-Claim.cshtml");
                            Response.End();
                        }
                    }
                }
                catch (System.Data.SqlClient.SqlException se)
                {
                    if (se.Number == 2601)
                    {
                        hasError = true;
                        errorMessage = "You have made a claim on this date already.";
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            } // if (!hasError)
                        
        } // if (Request.Form["actionButton"] == "submit")

        if (Request.Form["actionButton"] == "approval_submission")
        {
            try
            {
                if (KeppelLand.Controllers.ClaimController.SubmitClaimsToSupervisor(KeppelLand.Helpers.UserIdentityHelper.GetClaimantName()))
                {
                    hasSuccess = true;
                    successMessage = "Claims submitted";

                    // Reset fields to empty
                    frm_claimDate = string.Empty;
                    frm_claimStartWorkTime = string.Empty;
                    frm_claimEndWorkTime = string.Empty;
                    frm_claimStartOT = string.Empty;
                    frm_claimEndOT = string.Empty;
                    frm_claimHours_OT1_5 = string.Empty;
                    frm_claimHours_OT2_0 = string.Empty;
                    frm_claimHours_PH = string.Empty;
                    frm_claimHours_Less4H = string.Empty;
                    frm_claimHours_More4H = string.Empty;
                    frm_claimAllowance_Meal = string.Empty;
                    frm_claimAllowance_Shift = string.Empty;
                    frm_claimShiftType = string.Empty;
                    frm_claimRemark = string.Empty;
                    frm_claimTotalOTHours = "N/A";
                    frm_claimBreakHours = string.Empty;
                }
            }
            catch (KeppelLand.Controllers.ClaimException ex)
            {
                hasError = true;
                errorMessage = ex.Message;
            }
            catch (Exception)
            {
                throw;
            }
        } // if (Request.Form["actionButton"] == "approval_submission")

        if (Request.Form["actionButton"] == "remove")
        {
            string frm_actionId = Request.Form["actionId"].Trim();

            if (!string.IsNullOrEmpty(frm_actionId))
            {
                string id = KeppelLand.Helpers.CryptographyHelper.Decrypt(frm_actionId);

                if (!string.IsNullOrEmpty(id))
                {
                    if (KeppelLand.Controllers.ClaimController.RemoveClaim(KeppelLand.Helpers.UserIdentityHelper.GetClaimantName(), id))
                    {
                        hasSuccess = true;
                        successMessage = "Claim entry deleted.";
                    }
                }
            }
        } // if (Request.Form["actionButton"] == "remove")
        
        if (Request.Form["actionButton"] == "download")
        {
            byte[] fileBytes = KeppelLand.Controllers.ReportController.GetClaimsPendingSubmissionReport(
                Request.Form["download_format"],
                KeppelLand.Helpers.UserIdentityHelper.GetClaimantName(),
                KeppelLand.Entities.ClaimStatus.DRAFT);
            Response.Clear();
            Response.ContentType = KeppelLand.Helpers.TranslationHelper.GetContentType(Request.Form["download_format"]);
            Response.AddHeader("content-disposition", "attachment; filename=" + KeppelLand.Helpers.TranslationHelper.GetFileName(Request.Form["download_format"], "Claims"));
            Response.BinaryWrite(fileBytes);
            Response.Flush();
            Response.End();
        } // if (Request.Form["actionButton"] == "download")
        
    } // if (IsPost)
    
    if ((Request.QueryString.Count > 0) && (Request.QueryString["ID"] != null))
    {
        string id = KeppelLand.Helpers.CryptographyHelper.Decrypt(Request.QueryString["ID"]);
        claim = KeppelLand.Controllers.ClaimController.GetClaim(KeppelLand.Helpers.UserIdentityHelper.GetClaimantName(), id);
        if (claim != null)
        {
            frm_claimDate = KeppelLand.Helpers.FormatHelper.FormatDate(claim.ClaimDate);
            frm_claimStartWorkTime = KeppelLand.Helpers.FormatHelper.FormatTime(claim.StartWorkTime);
            frm_claimEndWorkTime = KeppelLand.Helpers.FormatHelper.FormatTime(claim.EndWorkTime);
            frm_claimStartOT = KeppelLand.Helpers.FormatHelper.FormatTime(claim.StartOverTime);
            frm_claimEndOT = KeppelLand.Helpers.FormatHelper.FormatTime(claim.EndOverTime);
            
            frm_claimHours_OT1_5 = claim.OT1_5.ToString();
            frm_claimHours_OT2_0 = claim.OT2_0.ToString();
            frm_claimHours_PH = claim.PH.ToString();
            frm_claimHours_Less4H = claim.RD4.ToString();
            frm_claimHours_More4H = claim.RD8.ToString();
            
            frm_claimAllowance_Meal = claim.AlwMeal.ToString();
            frm_claimAllowance_Shift = claim.AlwShft.ToString();
            frm_claimShiftType = claim.ShiftType;
            frm_claimRemark = claim.Remark;
            frm_claimTotalOTHours = claim.TotalOTHours;
            frm_claimBreakHours = claim.BreakHours.ToString();
            
        }
    }

    // Other normal get operations
    claimList = KeppelLand.Controllers.ClaimController.GetClaimList(KeppelLand.Helpers.UserIdentityHelper.GetClaimantName(), KeppelLand.Entities.ClaimStatus.DRAFT);
    claimSummary = KeppelLand.Controllers.ClaimController.GetClaimSummary(KeppelLand.Helpers.UserIdentityHelper.GetClaimantName(), KeppelLand.Entities.ClaimStatus.DRAFT);
}

<div class="container-fluid main-content" role="main">
    
    @if (hasError)
    {
    <div class="alert alert-danger alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <strong>Warning!</strong> @errorMessage
    </div>
    }
    
    @if (hasSuccess)
    {
        <div class="alert alert-success alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <strong>Success!</strong> @successMessage
        </div>
    }

    <form method="post" onsubmit="return validateAddClaim();">

        <h2>Edit Claims</h2>

        @RenderPage("~/Shared/Claim_Entry.cshtml", "EDIT", frm_claimDate, frm_claimStartWorkTime, frm_claimEndWorkTime, frm_claimStartOT, frm_claimEndOT, frm_claimHours_OT1_5, frm_claimHours_OT2_0, frm_claimHours_PH, frm_claimHours_Less4H, frm_claimHours_More4H, frm_claimAllowance_Meal, frm_claimAllowance_Shift, frm_claimShiftType, frm_claimRemark, frm_claimTotalOTHours, frm_claimBreakHours)

    </form>

    @RenderPage("~/Shared/Claims_Pending_Submission.cshtml", claimList, claimSummary)

    <p>&nbsp;</p>

</div>

@RenderPage("~/Shared/Standard_Modals.cshtml")

<div class="modal fade" id="messageModal" tabindex="-1" role="dialog" aria-labelledby="messageModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="messageModalLabel">Message</h4>
            </div>
            <div class="modal-body" id="messageModalBody">
                <p>
                    <strong>Rejection Reason:</strong>
                </p>
                <p id="messageModal_rejected_reason">
                    Click OK to proceed with this action.<br />
                    Click Canel to abort this action.
                </p>

                <p>
                    <strong>Rejected By</strong><br />
                    <span id="messageModal_rejected_by"></span>
                </p>
                <p>
                    <strong>Rejected Date</strong><br />
                    <span id="messageModal_rejected_date"></span>
                </p>
            </div>

            <div class="modal-footer">

                <button type="button" class="btn btn-primary" id="messageModal_OK" data-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="helpModal" tabindex="-1" role="dialog" aria-labelledby="helpModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="helpModalLabel">Help <small>(Edit Claim)</small></h4>
            </div>
            <div class="modal-body">
                <p>
                    Use this page to submit, or edit existing claims.<br />
                    To edit claims, follow the below instructions.
                </p>

                <p>To edit claims, follow the below instructions.</p>

                <div class="panel panel-default">
                    <div class="panel-heading">Instructions to edit existings claim(s)</div>
                    <div class="panel-body">

                        <ol>
                            <li>Claimant to enter claim date, official hours and overtime hours.</li>
                            <li>Claimant then fill in the overtime type.</li>
                        </ol>
                    </div>
                </div>

                <p>To submit claims, follow the below instructions.</p>

                <div class="panel panel-default">
                    <div class="panel-heading">Instructions to submit claims to supervisor</div>
                    <div class="panel-body">

                        <ol>
                            <li>Claimant to enter claim date, official hours and overtime hours.</li>
                            <li>Claimant then fill in the overtime type.</li>
                        </ol>
                    </div>
                </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="helpModal_Close" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
@section Scripts
{
    <script type="text/javascript" src="~/Scripts/kendo/2014.3.1119/kendo.ui.core.min.js"></script>
    <script type="text/javascript" src="~/Scripts/moment.js"></script>
    <script type="text/javascript" src="~/Scripts/moment-with-locales.js"></script>
    <script type="text/javascript" src="~/Scripts/app/claim_entry.js"></script>
    <script type="text/javascript">
        function download(format) {
            $("#approval_form #actionButton").val("download");
            $("#approval_form #download_format").val(format);
            $("#approval_form").submit();
        }

        function ShowMessageDialog(id) {
            // Some AJAX  to fetch message
            $("#messageModal_rejected_reason").text("Retrieving data...");
            $("#messageModal_rejected_by").text("Retrieving data...");
            $("#messageModal_rejected_date").text("Retrieving data...");
            var postJson = {
                id: id
            };
            $.ajax({
                type: "POST",
                url: "TestService.svc/DoWork",
                data: JSON.stringify(postJson),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (jsonData, status, xhr) {
                    detail = jsonData.d;
                    $("#messageModal_rejected_reason").text("Retrieving details...");
                    $("#messageModal_rejected_by").text("Retrieving details...");
                    $("#messageModal_rejected_date").text("Retrieving details...");
                    $('#messageModal').modal('show');
                    $("#messageModal_rejected_reason").html(detail.RejectReason);
                    $("#messageModal_rejected_by").text(detail.RejectorId);
                    $("#messageModal_rejected_date").text(detail.RejectDate);
                },
                error: function (xhr, status, err) {
                }
            });
        }

        (function ($) {
            "use strict";

            $(document).ready(function () {

                $("#approval_form button").click(function () {
                    $("#approval_form #actionButton").val(this.value);
                    $('#confirmationModal').modal('show');
                });

                // 
                $("#approval_submission_button").click(function () {
                    $("#approval_form #actionButton").val(this.value);
                    $('#confirmationModal').modal('show');
                });

                $("#pending_submission_claim_list button").click(function () {
                    $("#approval_form #actionButton").val("remove");
                    $("#approval_form #actionId").val(this.value);
                    $('#removeConfirmationModal').modal('show');
                });

                $("#confirmationModal_OK").click(function () {
                    $("#approval_form").submit();
                });

                $("#removeConfirmationModal_OK").click(function () {
                    $("#approval_form").submit();
                });

                $("#claimHours_Less4H, #claimHours_More4H").change(function () {
                    if (this.id === "claimHours_Less4H") {
                        $("#claimHours_More4H").prop("checked", false);
                    } else if (this.id === "claimHours_More4H") {
                        $("#claimHours_Less4H").prop("checked", false);
                    }
                });

            });

    }(jQuery));

    </script>
}